package com.dmall.algorithm.chapter01;

public class Leetcode21V1 {

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode start = null;
        ListNode start1 = null;

        if (l1 == null && l2 == null) {
            return null;
        } else if (l1 == null) {
            start = l2;
        } else if (l2 == null) {
            start = l1;
        }

        if (start == null) {
            start = l1.val > l2.val ? l2 : l1;
            start1 = l1.val <= l2.val ? l2 : l1;
        }
        ListNode cur1 = start;
        ListNode cur2 = start1;
        while (cur1 != null || cur2 != null) {
            if (cur1.next != null && cur2 != null) {
                if (cur1.next.val < cur2.val) {
                    cur1 = cur1.next;
                } else {
                    ListNode temp = cur1.next;
                    cur1.next = cur2;
                    cur2 = cur2.next;
                    cur1.next.next = temp;
                    cur1 = cur1.next;
                }
            } else if (cur1.next == null && cur2 != null) {
                cur1.next = cur2;
                break;
            } else if (cur1.next != null && cur2 == null) {
                break;
            } else {
                break;
            }
        }
        return start;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(-9);
        ListNode l2 = new ListNode(5);
        l1.next = new ListNode(3);

        l2.next = new ListNode(7);
        Leetcode21V1 leetcode21 = new Leetcode21V1();
        ListNode result = leetcode21.mergeTwoLists(l1, l2);
        while (result != null) {
            System.out.print(result.val);
            System.out.print("->");
            result = result.next;
        }
        System.out.print("NULL");
        System.out.println();
    }
}
